package com.nettylern.nio;


import sun.nio.ch.IOUtil;

import java.io.*;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author liliang
 * @date 2019/12/8.
 */
public class FileNioCopy {

    public static void main(String[] args) {
        String filePath = "/Users/liliang/Downloads/简历.docx";
        String destPath = "/Users/liliang/Downloads/简历NioCopy.docx";
        File file = new File(filePath);
        File destFile = new File(destPath);
        if (!destFile.exists()) {
            try {
                boolean newFile = destFile.createNewFile();
                if (!newFile) {
                    System.out.println("创建失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        long startTime = System.currentTimeMillis();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try {
            fis = new FileInputStream(file);
            fos = new FileOutputStream(destFile);
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int inLen = -1;
            while ((inLen = inChannel.read(byteBuffer)) != -1) {
                byteBuffer.flip();
                int outLen = 0;
                while ((outLen = outChannel.write(byteBuffer)) != 0) {
                    System.out.println("写入的字节数:" + outLen);
                }
                byteBuffer.clear();
            }
//            long size = inChannel.size();
//            long pos = 0;
//            long count = 0;
//            while (pos < size) {
//                //每次复制最多1024个字节，没有就复制剩余的
//                count = size - pos > 1024 ? 1024 : size - pos;
//                //复制内存,偏移量pos + count长度
//                pos += outChannel.transferFrom(inChannel, pos, count);
//            }
            outChannel.force(true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            close(fis);
            close(fos);
            close(inChannel);
            close(outChannel);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("文件复制毫秒数:" + (endTime - startTime));
    }

    private static void close(Closeable closeable) {
        if (closeable == null) {
            return;
        }
        try {
            closeable.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
